import pandas as pd
import yaml

from General.ConfigLoader import load_config
from General.DatabaseReader import DatabaseReader

# 读取yaml配置文件
config = load_config()
node_code_index_map_filepath = config['filepath']['node_code_index_map']

def generate_node_code_index_map(db_reader, output_file_path=node_code_index_map_filepath):
    """
    生成地图节点（包括电梯）的索引映射，为节点分配唯一index
    """

    # Step 2: 从 MySQL 数据库读取数据
    df_a = db_reader.read_robot_node()
    df_b = db_reader.read_robot_node_lift()

    # Step 3: 生成节点和电梯的索引映射
    node_index_map = {node_code: idx for idx, node_code in enumerate(df_a['node_code'].unique())}
    lift_index_map = {lift_code: idx + len(node_index_map) for idx, lift_code in enumerate(df_b['lift_code'].unique())}
    code_index_map = {**node_index_map, **lift_index_map}

    # 获取附加的节点信息
    additional_info = df_a.set_index('node_code')[['node_x', 'node_y', 'map_code']].to_dict('index')

    # 创建结果 DataFrame
    code_index_list = []
    for code, index in code_index_map.items():
        entry = {'code': code, 'index': index}
        if code in additional_info:
            entry.update({'is_lift': 0})
            entry.update(additional_info[code])
        else:
            entry.update({'is_lift': 1})
        code_index_list.append(entry)

    code_index_df = pd.DataFrame(code_index_list)

    # 将 DataFrame 保存到 Excel 文件
    code_index_df.to_excel(output_file_path, index=False)



if __name__ == '__main__':
    db_reader = DatabaseReader()
    generate_node_code_index_map(db_reader)